﻿using DevTeam;
using System;
using System.Data;

namespace ConfExpert.Forms.ImportWizards
{
    public partial class Destex_LF_Tip1 : XITopCekiListesi
    {
        int YuklemeId;
        public Destex_LF_Tip1(int YuklemeId) :
            base(YuklemeId)
        {
            InitializeComponent();

            this.YuklemeId = YuklemeId;
            Init("Destex LF Tip1 Çeki Listesi", true);
            this.FileDone += DestexTip1_FileDone;
        }

        void DestexTip1_FileDone(DataSet ds, string FileName)
        {
            DataTable dt = ds.Tables[0];
            DataRowCollection rows = dt.Rows;
            DataColumnCollection cols = dt.Columns;
             
            int orderLineStart = -1;
            int orderLineEnd = -1;
            
            string invoiceNo = "";
            decimal total = -1;
            DateTime orderDate = DateTime.MinValue;

            for (int i = 0; i < rows.Count; i++)
            {
                DataRow dr = rows[i];
                if (dr[6].ToStr().ToUpper().Replace("İ","I") == "INVOICE NO.")
                {
                    invoiceNo = rows[i + 1][6].ToStr();
                }
                else if (dr[6].ToStr().ToUpper() == "DATE:")
                {
                    string date = dr[7].ToStr();
                    int year = date.Substring(0, 4).ToInt(-1);
                    int month = date.Substring(4, 2).ToInt(-1);
                    int day = date.Substring(6, 2).ToInt(-1);
                    orderDate = new DateTime(year, month, day);
                }
                else if (
                    dr[0].ToStr().ToUpper().Contains("CT/NO") &&
                    dr[1].ToStr().ToUpper().Contains("ORDER.NO") &&
                    dr[2].ToStr().ToUpper().Contains("COL.NO") &&
                    dr[3].ToStr().ToUpper().Contains("D/") &&
                    dr[4].ToStr().ToUpper().Contains("RLS") &&
                    dr[5].ToStr().ToUpper().Contains("QUANTITY") &&
                    dr[6].ToStr().ToUpper().Contains("N.W.") &&
                    dr[8].ToStr().ToUpper().Contains("MEAS.") &&
                    rows[i + 1][6].ToStr().ToUpper().Contains("(KGS)") &&
                    rows[i + 1][8].ToStr().ToUpper().Contains("(CBM)") &&
                    rows[i + 2][0].ToInt(-1) > -1)
                {
                    orderLineStart = i+2;
                }

                else if (
                    orderLineStart  > -1 &&
                    orderLineEnd == -1 &&
                            i > orderLineStart  &&
                            
                            dr[0].ToStr() == "" &&
                            dr[1].ToStr() == ""
                    )
                {
                    orderLineEnd = i-1;
                }
                else if (orderLineEnd > -1 &&
                    dr[0].ToStr().ToUpper().Contains("TTL")
                    )
                {
                    string ttlLine = dr[0].ToStr();
                    var p1 = ttlLine.Split(':');
                    var p2 = p1[1].Split(new string[] { "MRS" }, StringSplitOptions.RemoveEmptyEntries);
                    total = p2[0].Trim().ToDecimal(-1);                    
                }
            }

            /*
            DataTable Article = new DataTable();
            Article.Columns.Add("RowIndex", typeof(int));
            Article.Columns.Add("OrderNo", typeof(string));
            Article.Columns.Add("Article", typeof(string));
            Article.Columns.Add("Qty", typeof(decimal));
            Article.Columns.Add("ProductId", typeof(int));

            for (int i = orderLineStart; i < orderLineEnd + 1; i++)
            {
                DataRow dr = rows[i];
                int rowIndex = dr[0].ToInt(-1);
                string orderNo = dr[1].ToStr();
                string sheetName = dr[2].ToStr().Split(' ')[0];
                string qtys = dr[5].ToStr();
                foreach (string qty in qtys.Split('=')[0].Split('+'))
                {
                    DataRow drNew = Article.NewRow();
                    drNew["RowIndex"] = rowIndex;
                    drNew["OrderNo"] = orderNo;
                    drNew["Article"] = sheetName.Trim();
                    drNew["Qty"] = qty.Trim().ToDecimal(-1);
                    Article.Rows.Add(drNew);
                }
            }



            var distinctValues = Article.AsEnumerable()
                        .Select(row => new
                        {
                            Kod = row.Field<string>("Article"),
                        })
                        .Distinct().ToList();

         

            string codes = string.Join(",", Array.ConvertAll(distinctValues.ToArray(), i => i.Kod));
            
            DataTable dtId =  AppSession.DataManager.ExecuteDataTable("GetProductIdByCode", codes);
            foreach (DataRow drParsed in Article.Rows)
            {
                DataRow[] drIds = dtId.Select("Kod='" + drParsed["Article"] + "'");
                if (drIds.Length == 1)
                    drParsed["ProductId"] = (int)drIds[0]["ProductId"];
            }


            foreach (DataRow drParsed in Article.Rows)
            {
                if (Article.Select("Article='"+drParsed["Article"]+"'").Length == 0)
                {
                    DataRow drArticle = Article.NewRow();
                    drArticle["Article"] = drParsed["Article"];
                    drArticle["ProductId"] = drParsed["ProductId"];
                    Article.Rows.Add(drArticle);
                }
                DataRow drRoll = Roll.NewRow();
                drRoll["RowIndex"] = drParsed["RowIndex"];
                drRoll["OrderNo"] = drParsed["OrderNo"];
                drRoll["Qty"] = drParsed["Qty"];
                drRoll["Article"] = drParsed["Article"];
                Roll.Rows.Add(drRoll);
            }

            MasterGrid.Init(Article);
            MasterGrid.AddDetailGrid(DetailGrid, "Article");
            MasterGrid.SutunEkle("TotalQty", typeof(decimal), "SUM(Child({FK}).Qty)");
            MasterGrid.SutunEkle("RollCount", typeof(int), "COUNT(Child({FK}).Article)");
            //MasterGrid.MakeColumnInvisible("ProductId");
            DetailGrid.MakeColumnInvisible("Article");


            MasterGrid.AddSummary();
            MasterGrid.AddSummary("TotalQty","RollCount");

            DetailGrid.AddSummary();
            DetailGrid.AddSummary("Qty");

            MasterGrid.OptionsView.ShowViewCaption = true;
            MasterGrid.ViewCaption = string.Format("{0}: [{1}]", invoiceNo, orderDate.ToString("dd.MM.yyyy"));
            
            MasterGrid.MakeReadOnly("ProductId");            
            DetailGrid.MakeReadOnly();

            DetailGrid.Columns["Qty"].Width = 100;
            */
        }


    }
}

